import sensor, image, time
from pyb import Pin
from pyb import LED
import pyb

sensor.reset() # 初始化摄像头
sensor.set_pixformat(sensor.GRAYSCALE) # 格式为 RGB565.
sensor.set_framesize(sensor.QVGA)
sensor.skip_frames(10) # 跳过10帧，使新设置生效
sensor.set_auto_whitebal(False)
led1 = pyb.LED(1)
led2 = pyb.LED(2)
led3 = pyb.LED(3)
i=0
start = pyb.micros()

while(True):
    p_out1 = Pin('P1', Pin.OUT_PP)#设置p_out为输出引脚
    p_out2 = Pin('P2', Pin.OUT_PP)#设置p_out为输出引脚
    p_out3 = Pin('P3', Pin.OUT_PP)
    THRESHOLD = (0, 100) # Grayscale threshold for dark things...

    ROI1=(0,80,320,40)
    ROI2=(0,0,60,20)
    ROI3=(100,0,220,20)
    ROI4=(0,0,160,20)

    img = sensor.snapshot().binary([THRESHOLD])#线设置为白色，其他为黑色


    statistics1=img.get_statistics(roi=ROI1)
    statistics2=img.get_statistics(roi=ROI2)
    statistics3=img.get_statistics(roi=ROI3)
    statistics4=img.get_statistics(roi=ROI4)


    if(statistics1.mean()>55):
        p_out1.high()
        p_out2.low()
        p_out3.low()
        led1.on()
    elif(statistics2.mean()>80 and statistics3.mean()>15 ):
        p_out1.low()
        p_out2.high()
        p_out3.low()
        led3.on()

    else:
        p_out1.low()
        p_out2.low()
        p_out3.low()
        led1.off()
        led2.off()
        led3.off()

    #画方框标识识别区域
    img.draw_rectangle(ROI1)
    img.draw_rectangle(ROI2)
    img.draw_rectangle(ROI3)


    # 计算运行时间
    x=pyb.elapsed_micros(start)//100000/7.9
    i=i+1
    if(x>30):
        p_out3.high()
        print('ok')
    else:
        p_out3.low()
        print('nook')


    print(statistics2.mean())
